package cn.jzq.kotoba.modules.rabbitmq.demo;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * rabbitmq RabbitReceiver
 * @author jzq
 * @date 2018-09-08
 */
public class RabbitReceiver {


    private final static String QUEUE_NAME = "hello";

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        // 此处也声明了队列，因为消费者可能先被启动。接收方试图消费消息之前，需要确保队列已经存在
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

        // 接收方打算通知服务器向其传递队列中的消息。因为RabbitMQ异步推送消息，接收方需要提供一个回调接口，
        // 在准备好使用消息之前，以对象的形式缓冲消息。这就是DefaultConsumer类存在的意义
        Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String message = new String(body, "UTF-8");
                System.out.println(" [x] Received '" + message + "'");
            }
        };
        channel.basicConsume(QUEUE_NAME, true, consumer);
    }

}
